<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\cms\controller;
use think\admin\Controller;
use think\admin\service\AdminService;

/**
 * 气源供求信息台账
 * Class Gassupply
 * @package app\wechat\controller
 */
class Gassupply extends BaseController
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'CmsGasSupplyDemand';

    /**
     * 气源供求信息
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = "气源供求信息";
        $map = ['is_deleted' => '0'];
        //根据like后的字段来进行搜索
        $this->_query($this->table)->like('company,month')
            ->where($map)->order('id desc')->page();
    }

    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 清理权限节点
            AdminService::instance()->clearCache();
        }
    }

    /**
     * 添加气源供应信息
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function add()
    {

        if ($this->request->isGet()) {
            $this->_applyFormToken();
            $this->_form($this->table, 'form');
        } else {

            $update = $this->request->post('data', []);
            $update[ 'create_by']   = AdminService::instance()->getUserId();
            $update[ 'update_at'] = $update[ 'create_at'] = time();
            if ($this->app->db->name($this->table)->insert($update) !== false) {
                $this->success('添加成功！','javascript:history.back()');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    /**
     * 编辑气源供应信息
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {

        $this->id = $this->request->get('id');
        $map = array("id" => $this->id);
        if (empty($this->id)) $this->error('参数错误，请稍候再试！');
        if ($this->request->isGet()) {
            if ($this->request->get('output') === 'json') {
                $this->success('获取数据成功！', $this->app->db->name($this->table)->where($map)->find());
            } else {
                $this->title = '编辑信息';
                $this->_applyFormToken();
                $this->_form($this->table, 'form');
            }
        }else{
            $data = $this->request->post('data', []);
            $data['update_at'] = time();
            if ($this->app->db->name($this->table)->where($map)->update($data) !== false) {
                $this->success('信息更新成功！', 'javascript:history.back()');
            } else {
                $this->error('信息更新失败，请稍候再试！');
            }
        }

    }

    /**
     * 删除气源供应信息
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 导出
     */
    public function export(){

        $origin = $this->request->get("company");
        $month = $this->request->get("month");
        $title = [
            array("month","月份"),
            array("company","企业名称"),
            array("company_man","填表人"),
            array("company_phone","联系方式"),
            array("pip_supply","管道气接收量（万方）"),
            array("lng_supply","LNG接收量（吨）"),
            array("deman_qty","需求量（万方/天）"),
            array("lack_qty","缺口量（万方/天）"),
            array("reserve_qty","储备量（万方）"),
            array("use_days","使用天数"),
            array("methods","解决措施"),
            array("notes","备注")
        ];
        $data = $this->prepareExportData($month, $origin);
        $this->exportExcel($title, $data);

    }

    private function prepareExportData($month, $company){
        $map = [];
        if($month) $map['month'] = $month;
        $query = $this->app->db->name($this->table)->where($map);
        if($company) $query = $query->whereLike("company","%".$company."%");
        return $query->order("id desc")->select();
    }

    public function import(){
        //$inputFileName = "F:\\phpStudy\\GasPortalProject\\temp\\01simple.xlsx";
        //$inputFileName = "http://127.0.0.1:9500/upload/63/1fcfb478ee9a562f929784a1b44e64.xlsx";
        $inputFileName = $this->request->request("url");
        $inputFileName = $this->filerFilePath($inputFileName);

        $fields = [
            "month", "company", "company_man", "company_phone","pip_supply",
            "lng_supply", "deman_qty", "lack_qty", "reserve_qty", "use_days",
            "methods", "notes"
        ];
        $res = $this->importExcel($inputFileName, $fields,2,array());
        if($res['status']==0){
            $this->error($res['info']);
        }
        $this->success($res['info']);

    }

}
